package com.tyc.flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 流处理实现 WordCount 从socket中读取数据
 *
 * @author tyc
 * @version 1.0
 * @date 2022-11-16 13:41:08
 */
public class WordCountStreamSocket {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment();
        /**
         * 下载 https://eternallybored.org/misc/netcat/ 解压，配置环境变量
         * 启动服务：nc -l 8006
         * 启动当前服务
         * 黑窗口输入文本，查看当前控制台输出
         */
        DataStreamSource<String> dataStream = env.socketTextStream("127.0.0.1", 8006);
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = dataStream.flatMap(new MyStreamFlatMap())
                .keyBy(item->item.f0)
                .sum(1);
        result.print();
        env.execute();
    }

    private static class MyStreamFlatMap implements FlatMapFunction<String, Tuple2<String, Integer>> {
        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] words = s.split(" ");
            for(String word:words) {
                collector.collect(new Tuple2<>(word,1));
            }
        }
    }
}
